package com.emcom.gotour.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadService {

	private String uploadPath = "htdocs/images/";

	private String imagePath = "images/";

	public boolean upload(MultipartFile file) {
		if(file == null) {
			return false;
		}
		try {
			if(!this.uploadPath.endsWith("/")) {
				this.uploadPath = this.uploadPath.concat("/");
			}
			File outputPathFile = new File(this.uploadPath);
			if(!outputPathFile.exists()) {
				FileUtils.forceMkdir(outputPathFile);
			}
			byte[] fileBytes = file.getBytes();
			if(fileBytes.length == 0) {
				return false;
			}
			File uploadFile = new File(this.uploadPath.concat(file.getOriginalFilename()));
			OutputStream outputStream = new FileOutputStream(uploadFile);
			outputStream.flush();
			outputStream.write(fileBytes);
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public String getFileUrl(MultipartFile file) {
		if(StringUtils.isEmpty(file.getOriginalFilename())) {
			return "";
		}
		return this.imagePath.concat(file.getOriginalFilename());
	}

	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}

	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
	}

}
